package com.hainingtong.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hainingtong.user.dao.AuthMapper;
import com.hainingtong.user.dao.PermissionMapper;
import com.hainingtong.user.dao.RoleMapper;
import com.hainingtong.user.dao.UserMapper;
import com.hainingtong.user.entity.*;
import com.hainingtong.user.exception.NicknameExistsException;
import com.hainingtong.user.exception.PrincipalExistsException;
import com.hainingtong.user.service.UserService;
import com.hainingtong.user.shiro.token.LoginType;
import com.hainingtong.user.util.page.PageResult;
import com.hainingtong.user.util.page.PageUtils;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Transactional
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    AuthMapper authMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    RoleMapper roleMapper;

    @Override
    public SysUser findUserById(int userId) {
        return userMapper.findById(userId);
    }


    @Override
    @Transactional
    public SysUser register(String nickname, String principal, String credential, String loginType)  {

        try {
            SysUser user = new SysUser();
            user.setNickname(nickname);

            userMapper.insert(user);

            SysAuth auth = new SysAuth();
            auth.setUserId(user.getId());
            auth.setPrincipal(principal);

            credential = BCrypt.hashpw(credential, BCrypt.gensalt());
            auth.setCredential(credential);

            auth.setLoginType(LoginType.valueOf(loginType));

            authMapper.insert(auth);
            return user;
        } catch (DuplicateKeyException e) {
            if (Objects.requireNonNull(e.getMessage()).contains("nickname")) {
                throw new NicknameExistsException();
            } else if (e.getMessage().contains("principal_login_type_unique_index")) {
                throw new PrincipalExistsException();
            }
            throw e;
        }
    }

    @Override
    public SysAuth findAuthByPrincipalAndType(String principal, String type) {
        return authMapper.findByPrincipalAndType(principal, type);
    }

    @Override
    public SysUser findUserByPrincipalAndType(String principal, String type) {
        SysAuth auth = this.findAuthByPrincipalAndType(principal, type);
        if (auth == null) {
            return null;
        }
        return userMapper.findById(auth.getUserId());
    }

    @Override
    public boolean isUserExists(String principal, String type) {
        return authMapper.isAuthExits(principal, type) == 1;
    }

    @Override
    public PageResult getUsers(int page, int size) {

        PageHelper.startPage(page, size);
        List<SysUser> users = userMapper.findAll();
        return PageUtils.getPageResult(new PageInfo<>(users));
    }

    @Override
    public List<SysPermission> findAllPermissions() {
        return permissionMapper.findAll();
    }

    @Override
    public List<SysRole> findAllRoles() {
        return roleMapper.findAll();
    }

    @Cacheable(cacheNames = "UserWithRolesAndPermissions")
    @Override
    public UserWithRolesAndPermissions findUserWithRolesAndPermissions(int userId) {
        SysUser u = userMapper.findById(userId);
        UserWithRolesAndPermissions user = new UserWithRolesAndPermissions(u);



        List<SysRole> roles = userMapper.findRolesByUserId(userId);
        user.setRoles(roles);

        List<Integer> roleIds = new ArrayList<>();
        for (SysRole role : roles) {
            roleIds.add(role.getId());
        }

        List<SysPermission> permissions = roleMapper.findPermissionsByRoleIds(roleIds);
        user.setPermissions(permissions);
        return user;
    }

}
